'use strict'

import axios from 'axios'

export class ApiError extends Error {
  code
  constructor(code, message) {
    super(message)
    this.code = code
  }
}

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: process.env.API_BASE
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
}

const global = {
  autoLog: false
}

const _axios = axios.create(config)

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // 方便调试的自动输出
    if (global.autoLog) {
      // eslint-disable-next-line
      console.log(response.data)
    }
    // Do something with response data
    return response.data
  },
  function(error) {
    // Do something with response error
    if (error.response && error.response.data && error.response.data.message) {
      return Promise.reject(new ApiError(error.response.status, error.response.data.message))
    }
    return Promise.reject(error)
  }
)

export default _axios

/**
 * 设置调用API时是否自动log
 * @param {Boolean} value
 */
export function setAutoLog(value) {
  global.autoLog = value
}
